<?php

namespace App\Service;

use GuzzleHttp\Client;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Di\Annotation\Inject;

class ArticleService
{
    /**
     * @Inject
     * @var ValidatorFactoryInterface
     */
    protected $validatorFactory;

    protected $apiKey = 'sk-adab94d73dc147859c5dd6b891fab1f9';

    protected $webPromptMap = [
        'lovelypetpal' => 'petpalPrompt'
    ];

    public function generateArticle(array $data): array
    {
        $promptMethod = $this->webPromptMap[$data['webname']] ?? null;
        if (!$promptMethod || !method_exists($this, $promptMethod)) {
            throw new \InvalidArgumentException('不支持该网站的prompt生成');
        }

        $prompt = $this->{$promptMethod}($data);

        $client = new Client([
            'base_uri' => 'https://api.deepseek.com',
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ],
            'verify' => false, // 生产环境建议配置正确的证书
            'timeout' => 80, // 总超时时间60秒
            'connect_timeout' => 10, // 连接超时10秒
            'http_errors' => false // 不抛出HTTP错误异常
        ]);

        try {
            $response = $client->post('/chat/completions', [
                'json' => [
                    'model' => 'deepseek-chat',
                    'messages' => [
                        ['role' => 'system', 'content' => 'You are an expert SEO content writer.'],
                        ['role' => 'user', 'content' => $prompt]
                    ],
                    'stream' => false,
                    'max_tokens' => 3000 // 限制最大token数
                ],
                'timeout' => 80 // 单独请求超时55秒
            ]);


            $result = json_decode($response->getBody()->getContents(), true);

            if (!isset($result['choices'][0]['message']['content'])) {
                throw new \RuntimeException('API返回结构无效');
            }

            $rawContent = $result['choices'][0]['message']['content'];
            $cleanedContent = preg_replace('/^```json|```$/m', '', $rawContent);
            $contentData = json_decode(trim($cleanedContent), true);

            return $contentData;
        } catch (\Exception $e) {
            throw new \RuntimeException('API请求失败: '.$e->getMessage());
        }
    }

    /*
     * 宠物用品博文
     */
    private function petpalPrompt(array $data): string
    {
        $description = json_encode($data['description'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $images = json_encode($data['images'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        return <<<PROMPT
        # 指令
        作为专业的宠物用品谷歌SEO内容作家，请根据提供的产品数据创建一篇高度优化的英文博文。要求：
        1. 严格遵循2024年Google EEAT原则（专业性、权威性、可信度）
        2. 所有内容必须原创且符合语义SEO规范
        3. 返回标准JSON格式数据

         # 输入数据
        {
            "product_info": {
            "name": "{$data['name']}",
            "description": $description,
            "url": "{$data['url']}",
            "media": {
                "images": $images
                }
            },
            "seo_assets": {
            "primary_keyword": "{$data['keywords']}",
            "secondary_keywords": ["{$data['extensions']}"],
            "existing_metadata": {
                    "title": "{$data['meta_title']}",
                    "description": "{$data['meta_description']}"
                }
            },
            "content_guidelines": {
                "target_audience": "pet owners aged 25-45",
                "tone": "专业但友好，避免过度销售语言"
            }
        }
            
        # 输出要求
        {
            "post_title": {
                "description": "45-65字符的点击诱饵式标题",
                "rules": [
                    "必须包含主关键词 '{$data['keywords']}'",
                    "使用数字/疑问句/情感触发词（如'Proven', 'Ultimate'）",
                    "示例结构: '[数字] Best [产品类型] for [使用场景] (2025 Expert Pick)'"
                ],
                "example": "5 Best {$data['name']} for {$data['extensions']} (Vet-Approved 2024 Guide)"
            },
            "short_description": {
                "description": "100-160字符的摘要",
                "rules": [
                    "首句提出读者痛点（如'Struggling with...?'）",
                    "包含1次主关键词和1-2次语义变体",
                    "结尾使用行动号召（如'Discover how...'）"
                ]
            },
            "description": {
                "description": "800-1500词的详细内容（同时满足OpenCart格式与SEO要求）",
                "structure": [
                    "## HTML格式规范",
                    "&lt;div data-slate-node=\"element\" style=\"position: relative\"&gt;",
                    "&lt;p data-start=\"[随机900-3000]\" data-end=\"[随机900-3000]\"&gt;&lt;font face=\"Arial\"&gt;&lt;span style=\"font-size: 18px;\"&gt;[内容]&lt;/span&gt;&lt;/font&gt;&lt;/p&gt;",
                    "&lt;span style=\"font-size: 18px;\"&gt;&lt;/span&gt;",
                    "&lt;/div&gt;",
                    
                    "## SEO核心规则",
                    {
                        "keyword_density": "1.5-2%",
                        "heading_optimization": {
                            "H2": "必须包含LSI关键词（如'dog sweater sizing guide'）",
                            "H3": "使用长尾词变体（如'red winter dog clothing'）"
                        },
                        "external_links": [
                            "至少2个权威外链，以下来源中随机选择，使用nofollow属性：",
                            "- https://www.aspca.org （美国ASPCA，宠物保暖指南）",
                            "- https://www.rspca.org.uk （英国RSPCA，动物福利指南）",
                            "- https://www.bluecross.org.uk （英国Blue Cross，宠物健康建议）",
                            "- https://www.tierschutzbund.de （德国Tierschutzbund，动物保护）"
                        ]
                    },
                    
                    "## 内容与格式绑定规则",
                    {
                        "paragraph_1": "痛点场景 + &lt;strong&gt;产品名&lt;/strong&gt; + 解决方案预告",
                        "paragraph_2": "材质说明（&lt;strong&gt;关键特征&lt;/strong&gt; + 对比数据）",
                        "paragraph_3": "使用场景（季节/节日 + &lt;strong&gt;适用犬种&lt;/strong&gt;） + 插入产品图片（宽高288px）",
                        "paragraph_4": "设计细节（&lt;strong&gt;颜色/结构&lt;/strong&gt; + 尺寸指南）",
                        "paragraph_5": "专家背书（兽医/训犬师引述）",
                        "paragraph_6": "行动号召（再次强调&lt;strong&gt;产品名&lt;/strong&gt;）"
                    }
                ],
                "compatibility_rules": [
                    "所有H2标题需转换为&lt;strong&gt;标签包裹的强调文本",
                    "外部链接添加 target=\"_blank\" rel=\"nofollow\"",
                    "列表项使用&lt;span&gt;+换行符而非&lt;ul&gt;&lt;li&gt;",
                    "图片alt属性格式：alt=\"[产品名] [LSI关键词]\"",
                    "插入图片时使用以下格式：&lt;img src=\"[图片URL]\" alt=\"[产品名] [关键词]\" width=\"288\" height=\"288\" style=\"display: block; margin: 10px auto;\"&gt;"
                ],
                "validation_example": {
                    "html_snippet": "&lt;div data-slate-node=\"element\" style=\"position: relative;\"&gt;&lt;p data-start=\"1200\" data-end=\"1500\"&gt;&lt;font face=\"Arial\"&gt;&lt;span style=\"font-size: 18px;\"&gt;According to &lt;a href=\"https://www.rspca.org.uk\" target=\"_blank\" rel=\"nofollow\"&gt;RSPCA&lt;/a&gt;, &lt;strong&gt;small breed dogs&lt;/strong&gt; need winter protection. Our &lt;strong&gt;Red Heart Dog Sweater&lt;/strong&gt; addresses this with...&lt;/span&gt;&lt;/font&gt;&lt;/p&gt;&lt;img src=\"https://example.com/pet-sweater.jpg\" alt=\"Red Heart Dog Sweater winter dog clothing\" width=\"288\" height=\"288\" style=\"display: block; margin: 10px auto;\"&gt;&lt;p data-start=\"1500\" data-end=\"1800\"&gt;&lt;font face=\"Arial\"&gt;&lt;span style=\"font-size: 18px;\"&gt;The sweater features...&lt;/span&gt;&lt;/font&gt;&lt;/p&gt;&lt;span style=\"font-size: 18px;\"&gt;&lt;/span&gt;&lt;/div&gt;",
                    "seo_checklist":[
                        "主关键词出现次数：8-12次",
                        "LSI关键词覆盖率：100%",
                        "可读性分数 ≥70",
                        "图片alt属性包含主关键词",
                        "图片宽高固定为288px"
                    ]
                }
            }
        }

        # 必需返回格式
        {
            "post_title": "",
            "short_description": "",
            "description": "",
            "meta_tag_title": "",
            "meta_tag_description": "",
            "meta_keywords": "",
            "tags": "",
            "word_count": 0,
            "keyword_density": 0.0
        }
        PROMPT;
    }
}
